package com.rd.student.wulian.wanggaobo.week04;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RandomPicker {

    public static void main(String[] args) {
        String inputFile = "all.txt";
        String outputFile = "random.txt";
        int n = 3;

        List<String> allStudents = readNamesFromFile(inputFile);
        List<String> randomStudents = pickRandomStudents(allStudents, n);
        writeNamesToFile(randomStudents, outputFile);

        System.out.println("随机选出的同学名字已保存在 " + outputFile + " 文件中。");
    }

    private static List<String> readNamesFromFile(String filename) {
        List<String> names = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                names.add(line);
            }
        } catch (IOException e) {
            System.out.println("无法读取文件 " + filename);
            e.printStackTrace();
        }
        return names;
    }

    private static List<String> pickRandomStudents(List<String> students, int n) {
        List<String> randomStudents = new ArrayList<>();
        int totalStudents = students.size();
        if (n > totalStudents) {
            System.out.println("要选择的人数超过班级总人数。");
            return randomStudents;
        }

        Random random = new Random();
        List<Integer> indices = new ArrayList<>();
        for (int i = 0; i < totalStudents; i++) {
            indices.add(i);
        }
        Collections.shuffle(indices);

        for (int i = 0; i < n; i++) {
            randomStudents.add(students.get(indices.get(i)));
        }

        return randomStudents;
    }

    private static void writeNamesToFile(List<String> names, String filename) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            for (String name : names) {
                writer.write(name);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("无法写入文件 " + filename);
            e.printStackTrace();
        }
    }
}